# -*- coding: utf-8 -*-

'''eof
name:最近3年年均订单金额（不含当前订单）
code:EB05_Last3YearAvgOrderAmt
tableName:
columnName:
groups:中标信息模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import  json
import numpy as np
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None
def formatDate2(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y')
                    except:
                        date = None
        return date
    except:
        return None
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False
def EB05_Last3YearAvgOrderAmt():
    try:
        #最近三年时间
        three_year_ago = (datetime.datetime.now() - datetime.timedelta(days=36 * 30)).strftime("%Y%m%d")
        #政采中标信息
        # governmentProcurementInfo=ratingRequest.get("governmentProcurementInfo")
        governmentProcurementInfo = json.loads(ratingRequest.get("governmentProcurementInfo"))
        #供应商合同集合
        contractList=governmentProcurementInfo.get("contractList")
        #合同状态
        status=["6",6]
        isSelect=["0",0]
        amount=[]
        timecnt = []
        result_list = []
        if governmentProcurementInfo in null_type_list or contractList in null_type_list :
            return u'缺失值'
        else:
            for i in contractList:
                # 合同签订日期
                createTime = i.get('createTime')
                createTimeformat = formatDate(createTime)
                if i.get("isSelect") in null_type_list or  i.get("contractState") in null_type_list or \
                        i.get("totalAmount") in null_type_list   or isfloat( i.get("totalAmount"))==False or\
                        i.get("createTime") in null_type_list \
                        or (i.get("createTime")+i.get("totalAmount") )  in result_list \
                        or createTimeformat<three_year_ago:
                    amount.append(0)
                    timecnt.append(0)

                    continue
                elif i.get("isSelect") in isSelect  and  i.get("contractState") in status:
                    amount.append(float(i.get("totalAmount")))
                    timecnt.append(formatDate2(i.get("createTime")))
                    result_list.append(i.get("createTime")+i.get("totalAmount"))
                else:
                    amount.append(0)
                    timecnt.append(0)
                    print amount

        returnListNotZero = filter(lambda x: x != 0, timecnt)
        cnt = len(set(returnListNotZero))
        print cnt
        if cnt==0:
            return 0
        else:
            return sum(amount)/cnt

    except:
        return u'缺失值'

if __name__ == '__main__':
    file_obj = open(r'E:\\changjiang_bd\\EBjson20190926.json', 'r')
    content = file_obj.read()
    ratingRequest = json.loads(content)
    print EB05_Last3YearAvgOrderAmt()


result = EB05_Last3YearAvgOrderAmt()

